/*
 * @Description: 数据集中管理
 * @Author: Gaq
 * @Date: 2022-11-11 20:13:54
 * @LastEditTime: 2023-02-20 18:51:51
 * @LastEditors: Gaq
 */
import {createStore} from 'vuex'
import request from "@/utils/request";

export default createStore({
    state:{
        userId: null,
        // addressList 在订单页面展示的信息 没有默认地址置顶
        addressList:[], 
        //addressData 在个人中心页面展示的地址表格（默认地址置顶）
        addressData : [],
        isClicked:null,
        addressObj : {
                userId:  null,
                name: "",
                phoneNumber: "",
                region: "",
                detail: "",
                isDefault: 0,
            },
        dialogShow:false
    },
    mutations:{
        SET_USERID(state,value){
            state.userId = value
        },
      GET_ADDRESS_TABLE(state,value){
        state.addressData = value
       },
       SET_DIALOG(state,value){
        console.log('SET_DIALOG调用了',value)
        state.dialogShow = value
        console.log('state.dialogShow的值',state.dialogShow)
       },
       GET_ADDRESS_LIST(state,value){
        state.addressList = value
       },
    //    设置选中的地址
       SET_CLICKED(state,value){
        state.isClicked = value
       }
    },
    actions:{
        // val 用户的id
        getAddressList({commit},val){ 
               request.get(`/address/getPart/${val}`).then((res) => {
                    res.data.map((item) => {
                        if (item.isDefault == 1) {
                        const index = res.data.indexOf(item);
                        res.data.splice(index, 1);
                        res.data.unshift(item);
                        }
                    });
                    commit("GET_ADDRESS_TABLE",res.data)
                });
        },
        // val 地址对象
        deleteAddressObj({dispatch, commit},val){
            request.delete(`/address/deleteOne/${val.addressId}`).then((res) => {
                if (res.code == 0) {
                dispatch('getAddressList',val.userId)
                }
              });
        },
        updateAddressList({commit},id){
            request.get(`/address/getPart/${id}`).then((res) => {
                
                if(res.code == -1){
                    commit("GET_ADDRESS_LIST", res.data);
                } else{
                    commit("SET_CLICKED",res.data.findIndex(
                        (item) => item.isDefault == 1
                      ))
                    commit("GET_ADDRESS_LIST", res.data);
                    // console.log("addressList的值", addressList.value);
                }
               
              });
        }
    }
})